var express = require('express');
var router = express.Router();

/* GET home page. */
var Controller = require("../controlls");

router.get('/', function(req, res, next) {
  	res.render('index', { title: 'Express' });
});

//登录注册
router.get("/ajax/validate", function(req, res){
	var _userId = req.session._userId;
	if(_userId){
		Controller.User.findUserById(_userId, function(err, user){
			if(err){
				res.json(401, {mgs: err})
			}else{
				res.json(user);
			}
		})
	}else{
		res.json(401, null);
	}
});

router.post("/ajax/login", function(req, res){
	var user = {
		name: req.body.username,
		password: req.body.password
	}
	Controller.User.LoginUser(user, function(err, oner){
		if(err){
			res.json(500, {msg: err})
		}else{
			req.session._userId = oner._id;
			Controller.User.online(oner._id, function(err, mine){
				if(err){
					res.json(500, {msg: err})
				}else{
					res.json(mine);
				}
			})
		}
	})
})

router.post("/ajax/register", function(req, res){
	var user = {
		name: req.body.username,
		password: req.body.password
	}
	Controller.User.CreateUser(user, function(err, oner){
		if(err){
			res.json(500, {msg: err})
		}else{
			req.session._userId = oner._id;
			res.json(oner);
		}
	})
})

router.get("/ajax/layout", function(req, res){
	var _userId = req.session._userId;
	Controller.User.offline(_userId, function(err, user){
		if(err){
			res.json(500, {msg: err})
		}else{
			res.json(200);
			req.session.destroy();
		}
	})
})

module.exports = router;















